const { con, Result } = require('./common');

let Getlist = async (user_id) => {
	let res = new Result();
	let arr = [];
	let sql = `select * from appointment where  usera_id = ${user_id}`
	let [rows] = await con.execute(sql);
	for (let i = 0; i < rows.length; i++) {
		let sql1 = `select * from commodity where commodity_id = ${rows[i].commoditya_id}`;
		let [rows1] = await con.execute(sql1);
		arr[i] = rows1[0];
		arr[i].time = rows[i].time
	}

	res.msg = '查询成功';
	res.data = arr;
	return res;
}
let Getlist2 = async (commodity_id) => {
        let res = new Result();
        let arr = [];
	let arr1 = [];
	let i = 0;
        let sql = `select * from appointment where  commoditya_id = ${commodity_id}`
        let [rows] = await con.execute(sql);
        for (i = 0; i < rows.length; i++) {
                let sql1 = `select * from commodity where commodity_id = ${rows[i].commoditya_id}`;
                let [rows1] = await con.execute(sql1);
		let sql2 = `select user_name,user_pic from user where user_id = ${rows[i].usera_id}`;
		let [rows2] = await con.execute(sql2);
		arr1[i] = rows2[0];
                arr[i] = rows1[0];
                arr[i].time = rows[i].time;
        }
	for(let j = 0;j<i;j++){
		arr[j].user = arr1[j];
	}
        res.msg = '查询成功';
        res.data = arr;
        return res;
}
let Insert_appo = async (usera_id, commoditya_id,time) => {
	let res = new Result();
	let sql = `insert appointment values('${usera_id}','${commoditya_id}','${time}')`;
	let [rows] = await con.execute(sql);
	let sql2 = `select * from commodity where commodity_id = ${commoditya_id}`;
	let [rows2] = await con.execute(sql2);
	let sql1 = `update commodity set commodity_appoint = ${rows2[0].commodity_appoint + 1} where commodity_id = ${commoditya_id}`;
	let [rows1] = await con.execute(sql1);
	res.msg = '预约成功';
	return res;
}
let Delete_appo = async (user_id, commodity_id) => {
	let res = new Result();
	let sql = `delete from appointment where usera_id=${user_id} and commoditya_id = ${commodity_id}`;
	let [rows] = await con.execute(sql);
	let sql2 = `select * from commodity where commodity_id = ${commodity_id}`;
	let [rows2] = await con.execute(sql2);
	let sql1 = `update commodity set commodity_appoint = ${rows2[0].commodity_appoint - 1} where commodity_id = ${commodity_id}`;
	let [rows1] = await con.execute(sql1);
	res.msg = '取消预约成功';
	return res;
}
module.exports = { Getlist,Getlist2, Insert_appo, Delete_appo }
